package com.demohomework.homeworkdemo.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;

import java.util.Date;
import java.util.Map;

public class JwtUtil {
    private static final String KEY = "homework";
    private static final long EXPIRATION_TIME = 1000 * 60 * 60 * 12; // 12小时

    // 接收业务数据，生成token并返回
    public static String genToken(Map<String, Object> claims) {
        return JWT.create()
                .withClaim("claims", claims)
                .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .sign(Algorithm.HMAC256(KEY));
    }

    // 接收token,验证token,并返回业务数据
    public static Map<String, Object> parseToken(String token) {
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(KEY)).build();
            DecodedJWT decodedJWT = verifier.verify(token);
            return decodedJWT.getClaim("claims").asMap();
        } catch (JWTVerificationException e) {
            // 处理验证失败的情况
            e.printStackTrace();
            System.out.println("token验证失败");
            return null;
        }
    }
}
